package main

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"github.com/olivere/elastic/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"io"
	"log"
	"mxshop_srvs/goods_srv/model"
	"os"
	"strconv"
	"time"
)

func genMd5(code string) string {
	Md5 := md5.New()
	_, _ = io.WriteString(Md5, code)
	return hex.EncodeToString(Md5.Sum(nil))
}

func main() {
	Mysql2Es()
}

func Mysql2Es() {
	//初始化连接
	dsn := "root:root@tcp(localhost:13316)/mxshop_goods_srv?charset=utf8&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), //io writer
		logger.Config{
			SlowThreshold: time.Second, //慢SQL 阈值
			LogLevel:      logger.Info, //Log level
			Colorful:      true,        //禁用彩色打印
		},
	)
	//全局模式
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	//设置全局的logger 这个logger在我们执行每一个sql语句的时候都会打印每一行sql
	//sql 才是最重要的
	//定义一个表结构,将表结构直接生成对应的表- migrations
	// 迁移 schema
	//_ = db.AutoMigrate(&model.Category{}, &model.Brands{}, &model.GoodsCategoryBrand{}, &model.Banner{}, &model.Goods{})
	host := "http://192.168.140.130:9200"
	//这里必须将sniff设置为false,因为使用 olivere/elastic连接es时,发现连接地址明明输入的时候是外网地址,
	//但是连接时会自动转换成内网地址或者docker中的ip地址,导致服务连不上
	logger := log.New(os.Stdout, "mxshop:", log.LstdFlags) //设置跟踪日志
	client, err := elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false), elastic.SetTraceLog(logger))
	if err != nil {
		panic(err)
	}
	var goods []model.Goods
	if tx := db.Find(&goods); tx.Error != nil {
		panic(tx.Error)
	}

	for _, g := range goods {
		esModel := model.EsGoods{
			ID:          g.ID,
			CategoryID:  g.CategoryID,
			BrandsID:    g.BrandsID,
			OnSale:      g.OnSale,
			ShipFree:    g.ShipFree,
			IsNew:       g.IsNew,
			IsHot:       g.IsHot,
			Name:        g.Name,
			ClickNum:    g.ClickNum,
			SoldNum:     g.SoldNum,
			FavNum:      g.FavNum,
			MarketPrice: g.MarketPrice,
			GoodsBrief:  g.GoodsBrief,
			ShopPrice:   g.ShopPrice,
		}
		_, err := client.Index().Index("goods").BodyJson(esModel).Id(strconv.Itoa(int(g.ID))).Do(context.Background())
		if err != nil {
			panic(err)
		}
		//【强调】docker 启动es的java_ops的内存设置大一些 否则会在运行过程中出现bad request
	}
}
